<?php

namespace app\admin\model;

use think\Model;

/**
 * Class Access
 *  商家用户权限模型
 * @package app\admin\model
 */
class AdminAccess extends Model
{
    protected $autoWriteTimestamp = true;
    protected $pk = "access_id";

    public $error;

    protected static function getAll($isShow = 1)
    {
        if ($isShow != -1) {
            $data = static::withoutGlobalScope()
                ->where('is_show', '=', $isShow)
                ->order(['sort' => 'asc', 'create_time' => 'asc'])
                ->select();
        } else {
            $data = static::withoutGlobalScope()
                ->order(['sort' => 'asc', 'create_time' => 'asc'])
                ->select();
        }

        return $data ? $data->toArray() : [];
    }

    /**
     * 获取权限列表
     */
    public function getList($pid = 0,$is_show=-1)
    {
        $all = static::getAll($is_show);
        $res = $this->recursiveMenuArray($all, $pid);
        return array_values($this->foo($res));
    }

    /**
     * 新增记录
     */
    public function add($data)
    {
        // 校验路径
        if (!$this->validate($data)) {
            return false;
        }
        $data['is_menu'] = $data['is_route'];
        return $this->save($data);
    }

    /**
     * 更新记录
     */
    public function edit($data)
    {
        if ($data['access_id'] == $data['parent_id']) {
            $this->error = '上级菜单不允许设置为当前菜单';
            return false;
        }
        // 判断上级角色是否为当前子级
        if ($data['parent_id'] > 0) {
            // 获取所有上级id集
            $parentIds = $this->getTopAccessIds($data['parent_id']);
            if (in_array($data['access_id'], $parentIds)) {
                $this->error = '上级菜单不允许设置为当前子菜单';
                return false;
            }
        }
        $data['is_menu'] = $data['is_route'];
        $data['redirect_name'] = ($data['is_route'] == 1) ? $data['redirect_name'] : '';
        return $this->save($data);
    }

    /**
     * 验证
     */
    private function validate($data)
    {

        if ($data['is_route']) {
            if ($data['path']) {
                $count = $this->where(['path' => $data['path']])->count();
                if ($count > 0) {
                    $this->error = '路径已存在，请重新更改';
                    return false;
                }
            } else {
                $this->error = '路径不能为空';
                return false;
            }
        } elseif (!$data['parent_id']) {
            $this->error = '按钮不能为根节点';
            return false;
        }
        return true;
    }

    public function getChildCount($where)
    {
        return $this->where($where)->count();
    }


    /**
     * 删除权限
     */
    public function remove($access_id)
    {
        return $this->where('access_id', '=', $access_id)->delete();
    }
    /**
     * 删除插件
     */
    public function removePlus()
    {
        return $this->save([
            'plus_category_id' => 0
        ]);
    }

    /**
     * 获取所有上级id集
     */
    public function getTopAccessIds($access_id, &$all = null)
    {
        static $ids = [];
        is_null($all) && $all = $this->getAll();

        foreach ($all as $item) {
            if ($item['access_id'] == $access_id && $item['parent_id'] > 0) {
                $ids[] = $item['parent_id'];
                $this->getTopAccessIds($item['parent_id'], $all);
            }
        }

        return $ids;
    }

    /**
     * 递归获取获取分类
     */
    public static function recursiveMenuArray($data, $pid)
    {
        $re_data = [];
        foreach ($data as $key => $value) {
            if ($value['parent_id'] == $pid) {
                $re_data[$value['access_id']] = $value;
                $re_data[$value['access_id']]['children'] = self::recursiveMenuArray($data, $value['access_id']);
            } else {
                continue;
            }
        }
        return $re_data;

    }

    /**
     * 格式化递归数组下标
     */
    public static function foo(&$ar)
    {
        if (!is_array($ar))
            return;
        foreach ($ar as $k => &$v) {
            if (is_array($v))
                self::foo($v);
            if ($k == 'children')
                $v = array_values($v);
        }
        return $ar;
    }

    /**
     * 更改显示状态
     */
    public function status($status)
    {
        return $this->save([
            'is_show' => $status
        ]);
    }

    /**
     * 获取所有插件
     */
    public static function getAllPlus()
    {
        $model = new static();
        $plus = $model->where('path', '=', '/plus/plus/index')->find();
        return $model->where('parent_id', '=', $plus['access_id'])
            ->where('plus_category_id', '=', 0)
            ->select();
    }

    /**
     * 保存插件分类
     * @param $data
     */
    public function addPlus($data)
    {
        $model = new self();
        return $model->where('access_id', '=', $data['access_id'])->save([
            'plus_category_id' => $data['plus_category_id']
        ]);
    }

    public function getError()
    {
        return $this->error;
    }
}